﻿using System;
using System.Collections.Generic;
using Newtonsoft.Json.Linq;
using TrinityAPI.Base;
using TrinityAPI.Base.Tools;
using AutoMailLib;

namespace TrinityAPI.AutoMail
{
    public class AbortTask : IAction
    {
        public JToken Invoke(JObject dataset, params JToken[] args)
        {
            var request = dataset.GetJsonObject("request");
            var constant = dataset.GetJsonObject("constant");
            var taskids = request.GetNecessaryJsonObjectList<string>("taskids");
            var remoteuri = constant.GetNecessaryJsonObjectStringValue("remoteuri", "constant");

            int totalSuccess = 0;
            int totalFailed = 0;
            foreach (var taskid in taskids)
            {
                try
                {
                    Common.GetEmailObj(remoteuri).EndRptDocProcess(taskid);
                    totalSuccess += 1;
                }
                catch (Exception ex)
                {
                    LogHelper.Error("Remove AutoMail task fail: " + taskid, ex);
                    totalFailed += 1;
                }
            }
            if (totalSuccess == 0)
                throw new Exception("@E999010001");

            return new JObject() {
                { "success", totalSuccess },
                { "failed", totalFailed }
            };
        }
    }
}
